package com.sdkj.fixed.asset.hc.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.github.pagehelper.PageHelper;
import com.sdkj.fixed.asset.api.hc.vo.in.IdParams;
import com.sdkj.fixed.asset.api.hc.vo.in.ReceiptSetGetPageParams;
import com.sdkj.fixed.asset.api.hc.vo.out.ReceiptSetGetPage;
import com.sdkj.fixed.asset.api.hc.vo.out.ReceiptSetGetPageNew;
import com.sdkj.fixed.asset.common.base.BaseMapper;
import com.sdkj.fixed.asset.common.base.BaseService;
import com.sdkj.fixed.asset.common.base.PageParams;
import com.sdkj.fixed.asset.common.exception.LogicException;
import com.sdkj.fixed.asset.common.utils.TimeTool;
import com.sdkj.fixed.asset.hc.mapper.*;
import com.sdkj.fixed.asset.pojo.hc.*;
import com.sdkj.fixed.asset.pojo.system.UserDateAuth;
import com.sdkj.fixed.asset.pojo.system.UserManagement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.text.DecimalFormat;
import java.util.List;

/***
 *
 * @author scx
 *
 */
@Service
public class ReceiptSetService extends BaseService<ReceiptSet> {

    private static Logger log = LoggerFactory.getLogger(ReceiptSetService.class);

    @Resource
    private ReceiptSetMapper mapper;

    @Resource
    private ReceiptSetProductMapper receiptSetProductMapper;

    @Resource
    private UserDataAuthMapper userDataAuthMapper;

    @Resource
    private ProductMapper productMapper;

    @Resource
    private CategoryMapper categoryMapper;

    @Resource
    private CategoryProductMapper categoryProductMapper;

    @Override
    public BaseMapper<ReceiptSet> getMapper() {
        return mapper;
    }

    @Resource
    private UserManagementMapper userManagementMapper;

    @Resource
    private QwertMapper qwertMapper;

    private void qwertyu(CategoryProduct categoryProduct, ReceiptSetProduct receiptSetProduct) {
        if (categoryProduct.getProductNum() == null) {
            categoryProduct.setTotalPrice("0.00");
            categoryProduct.setProductNum(0);
            categoryProduct.setPrice("0.00");
        }
        Integer totalNum = categoryProduct.getProductNum() + receiptSetProduct.getNum();
        Float totalPrice = Float.parseFloat(receiptSetProduct.getTotalPrice()) +
                Float.parseFloat(categoryProduct.getTotalPrice());
        DecimalFormat df = new DecimalFormat("0.00");//设置保留位数
        String format = "";
        if (totalNum == 0) {
            format = "0.00";
        } else {
            format = df.format((float) totalPrice / totalNum);
        }
        Qwert qwert = new Qwert();
        qwert.setBussinessDate(mapper.selectByPrimaryKey(receiptSetProduct.getReceiptId()).getBussinessDate());
        qwert.setCategoryId(categoryProduct.getCategoryId());
        qwert.setBeforeNum(categoryProduct.getProductNum());
        qwert.setBeforePrice(categoryProduct.getPrice());
        qwert.setBeforeTotalPrice(categoryProduct.getTotalPrice());
        qwert.setNumber(receiptSetProduct.getNumber());
        qwert.setCtime(DateUtil.now());
        qwert.setCuser(receiptSetProduct.getCuser());
        qwert.setProductId(receiptSetProduct.getProductId());
        qwert.setNum(receiptSetProduct.getNum());
        qwert.setPrice(receiptSetProduct.getPrice());
        qwert.setTotalPrice(receiptSetProduct.getTotalPrice());
        qwert.setAfterNum(totalNum);
        qwert.setAfterPrice(format);
        qwert.setAfterTotalPrice(df.format(totalPrice));
        qwertMapper.insertSelective(qwert);
    }

    private void qwertyui(CategoryProduct categoryProduct, ReceiptSetProduct receiptSetProduct) {
//        receiptSetProduct.setNum(receiptSetProduct.getNum()*-1);
//        receiptSetProduct.setTotalPrice(String.valueOf(Float.parseFloat(receiptSetProduct.getTotalPrice())*-1));

        if (categoryProduct.getProductNum() == null) {
            categoryProduct.setTotalPrice("0.00");
            categoryProduct.setProductNum(0);
            categoryProduct.setPrice("0.00");
        }
        Integer totalNum = categoryProduct.getProductNum() + receiptSetProduct.getNum()*-1;
        Float totalPrice = Float.parseFloat(categoryProduct.getTotalPrice()) +
                Float.parseFloat(String.valueOf(Float.parseFloat(receiptSetProduct.getTotalPrice())*-1));
        DecimalFormat df = new DecimalFormat("0.00");//设置保留位数
        String format = "";
        if (totalNum == 0) {
            format = "0.00";
        } else {
            format = df.format((float) totalPrice / totalNum);
        }
        Qwert qwert = new Qwert();
        qwert.setBussinessDate(mapper.selectByPrimaryKey(receiptSetProduct.getReceiptId()).getBussinessDate());
        qwert.setCategoryId(categoryProduct.getCategoryId());
        qwert.setBeforeNum(categoryProduct.getProductNum());
        qwert.setBeforePrice(categoryProduct.getPrice());
        qwert.setBeforeTotalPrice(categoryProduct.getTotalPrice());
        qwert.setNumber("");
        qwert.setCtime(DateUtil.now());
        qwert.setCuser(receiptSetProduct.getCuser());
        qwert.setProductId(receiptSetProduct.getProductId());
        qwert.setNum(receiptSetProduct.getNum()*-1);
        qwert.setPrice(receiptSetProduct.getPrice());
        qwert.setTotalPrice(receiptSetProduct.getTotalPrice().replaceAll("-",""));
        qwert.setAfterNum(totalNum);
        qwert.setAfterPrice(format);
        qwert.setAfterTotalPrice(df.format(totalPrice));
        qwertMapper.insertSelective(qwert);
    }

    /**
     * 减库存
     *
     * @param categoryProduct   仓库物品关联
     * @param receiptSetProduct 订单物品关联
     * @throws NumberFormatException 金额不对
     */
    private synchronized void minusNum(CategoryProduct categoryProduct, ReceiptSetProduct receiptSetProduct) throws NumberFormatException {
        //调整前单价
        receiptSetProduct.setPriceBefore(categoryProduct.getPrice());
        //调整前数量
        receiptSetProduct.setNumBefore(categoryProduct.getProductNum());
        //调整前总价
        receiptSetProduct.setTotalPriceBefore(categoryProduct.getTotalPrice());
        //计算总库存
        Integer totalNum = categoryProduct.getProductNum() - receiptSetProduct.getNum();
        if (totalNum < 0) {
            throw new LogicException("库存不足");
        }
        categoryProduct.setProductNum(totalNum);
        //计算出库后物品总价
        Float totalPrice = Float.parseFloat(categoryProduct.getTotalPrice()) - Float.parseFloat(receiptSetProduct.getTotalPrice());
        //计算出库后物品单价
        DecimalFormat df = new DecimalFormat("0.00");//设置保留位数
        String format = "";
        if (totalNum == 0) {
            format = "0.00";
        } else {
            format = df.format((float) totalPrice / totalNum);
        }
        categoryProduct.setTotalPrice(df.format(totalPrice));
        categoryProduct.setPrice(format);
        //调整后单价
        receiptSetProduct.setPriceAfter(format);
        //调整后数量
        receiptSetProduct.setNumAfter(totalNum);
        //调整后总价
        receiptSetProduct.setTotalPriceAfter(df.format(totalPrice));
        receiptSetProductMapper.updateByPrimaryKeySelective(receiptSetProduct);
        categoryProductMapper.updateByPrimaryKeySelective(categoryProduct);
    }

    /**
     * 加库存
     *
     * @param categoryProduct   仓库物品关联
     * @param receiptSetProduct 订单物品关联
     * @throws NumberFormatException 金额不对
     */
    private synchronized void addNum(CategoryProduct categoryProduct, ReceiptSetProduct receiptSetProduct) throws NumberFormatException {
        //调整前单价
        receiptSetProduct.setPriceBefore(categoryProduct.getPrice());
        //调整前数量
        receiptSetProduct.setNumBefore(categoryProduct.getProductNum());
        //调整前总价
        receiptSetProduct.setTotalPriceBefore(categoryProduct.getTotalPrice());
        //计算总库存
        Integer totalNum = categoryProduct.getProductNum() + receiptSetProduct.getNum();

        if (totalNum < 0) {
            throw new LogicException("调整后的库存不能是负数");
        }
        categoryProduct.setProductNum(totalNum);
        //计算入库后物品总价
        Float totalPrice = Float.parseFloat(receiptSetProduct.getTotalPrice()) +
                Float.parseFloat(categoryProduct.getTotalPrice());
        //计算入库后物品单价
        DecimalFormat df = new DecimalFormat("0.00");//设置保留位数
        String format = "";
        if (totalNum == 0) {
            format = "0.00";
        } else {
            format = df.format((float) totalPrice / totalNum);
        }
        categoryProduct.setTotalPrice(df.format(totalPrice));
        categoryProduct.setPrice(format);
        //调整后单价
        receiptSetProduct.setPriceAfter(format);
        //调整后数量
        receiptSetProduct.setNumAfter(totalNum);
        //调整后总价
        receiptSetProduct.setTotalPriceAfter(df.format(totalPrice));
        receiptSetProductMapper.updateByPrimaryKeySelective(receiptSetProduct);
        categoryProductMapper.updateByPrimaryKeySelective(categoryProduct);
    }

    /**
     * 新增
     *
     * @param entity
     * @return
     */
    @Transactional
    public ReceiptSet add(ReceiptSet entity) {
        if (categoryMapper.selectByPrimaryKey(entity.getCategoryId()).getIsCheck() == 1) {
            throw new LogicException("仓库在盘点中");
        }
        entity.setId(IdUtil.fastSimpleUUID());
        entity.setNumber("TZ" + TimeTool.getTimeDate14());
        mapper.insertSelective(entity);
        //调整单-耗材库存修改
        List<ReceiptSetProduct> receiptSetProductList = entity.getReceiptSetProductList();
        for (ReceiptSetProduct receiptSetProduct : receiptSetProductList) {
            if (receiptSetProduct.getPrice().length() > 32) {
                throw new LogicException("单价超出最大长度32位");
            }
            if (receiptSetProduct.getTotalPrice().length() > 32) {
                throw new LogicException("总价超出最大长度32位");
            }
            if (Float.parseFloat(receiptSetProduct.getPrice()) < 0) {
                throw new LogicException("调整单价不能为负数");
            }
            receiptSetProduct.setNumber(entity.getNumber());
            receiptSetProduct.setCuser(entity.getCuser());
            receiptSetProduct.setId(IdUtil.fastSimpleUUID());
            receiptSetProduct.setReceiptId(entity.getId());
            receiptSetProductMapper.insertSelective(receiptSetProduct);
            Example example = new Example(CategoryProduct.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("categoryId", entity.getCategoryId());
            criteria.andEqualTo("productId", receiptSetProduct.getProductId());
            //库存表改数
            List<CategoryProduct> categoryProducts = categoryProductMapper.selectByExample(example);
            try {
                qwertyu(categoryProducts.get(0), receiptSetProduct);
                addNum(categoryProducts.get(0), receiptSetProduct);
            } catch (NumberFormatException e) {
                log.error("金额格式错误");
            }
        }
        return entity;
    }

    /**
     * 修改
     *
     * @param entity
     * @param flag
     * @return
     */
    @Transactional
    public ReceiptSet edit(ReceiptSet entity, Boolean flag) {
        if (categoryMapper.selectByPrimaryKey(entity.getCategoryId()).getIsCheck() == 1) {
            throw new LogicException("仓库在盘点中");
        }
        if (categoryMapper.selectByPrimaryKey(entity.getCategoryId()).getState() != 1) {
            throw new LogicException("仓库不可用");
        }
        UserManagement user = userManagementMapper.selectByPrimaryKey(entity.getUserId());
        if (user.getDataIsAll() == 2) {
            Example examples = new Example(UserDateAuth.class);
            Example.Criteria criterias = examples.createCriteria();
            criterias.andEqualTo("type", 4);
            criterias.andEqualTo("userId", entity.getUserId());
            List<UserDateAuth> userDateAuths = userDataAuthMapper.selectByExample(examples);
            Boolean validate = false;
            for (UserDateAuth userDateAuth : userDateAuths) {
                if (userDateAuth.getAuthId().equals(entity.getCategoryId())) {
                    validate = true;
                }
            }
            if (!validate) {
                throw new LogicException("仓库不可用");
            }
        }
        ReceiptSet receiptSet = mapper.selectByPrimaryKey(entity.getId());
        entity.setBussinessDate(receiptSet.getBussinessDate());
        entity.setCtime(receiptSet.getCtime());
        entity.setCuser(receiptSet.getCuser());
        //删除原调整单-物品关联
        Example example = new Example(ReceiptSetProduct.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("receiptId", receiptSet.getId());
        //库存表改数
        List<ReceiptSetProduct> receiptSetProductList = receiptSetProductMapper.selectByExample(example);
        for (ReceiptSetProduct receiptSetProduct : receiptSetProductList) {
            Example example1 = new Example(CategoryProduct.class);
            Example.Criteria criteria1 = example1.createCriteria();
            criteria1.andEqualTo("categoryId", receiptSet.getCategoryId());
            criteria1.andEqualTo("productId", receiptSetProduct.getProductId());
            List<CategoryProduct> categoryProducts = categoryProductMapper.selectByExample(example1);
            try {
                minusNum(categoryProducts.get(0), receiptSetProduct);
            } catch (NumberFormatException e) {
                throw new LogicException("金额格式错误");
            }
            //删除入库详情
            receiptSetProductMapper.deleteByPrimaryKey(receiptSetProduct.getId());
        }
        if (flag) {
            mapper.updateByPrimaryKeySelective(entity);
            return entity;
        }
        //删除原入库单
        mapper.deleteByPrimaryKey(entity.getId());
        entity.setState(1);
        add(entity);
        return entity;
    }

    /**
     * 删除
     *
     * @param entity
     * @return
     */
    @Transactional
    public ReceiptSet del(IdParams entity) {
        ReceiptSet receiptSet = mapper.selectByPrimaryKey(entity.getId());
        receiptSet.setState(2);
        receiptSet.setUserId(entity.getEuser());
        if (categoryMapper.selectByPrimaryKey(receiptSet.getCategoryId()).getIsCheck() == 1) {
            throw new LogicException("仓库在盘点中");
        }
        //删除原调整单-物品关联
        Example example = new Example(ReceiptSetProduct.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("receiptId", receiptSet.getId());
        //库存表改数
        List<ReceiptSetProduct> receiptSetProductList = receiptSetProductMapper.selectByExample(example);
        for (ReceiptSetProduct receiptSetProduct : receiptSetProductList) {
            receiptSetProduct.setCuser(entity.getEuser());
            Example example1 = new Example(CategoryProduct.class);
            Example.Criteria criteria1 = example1.createCriteria();
            criteria1.andEqualTo("categoryId", receiptSet.getCategoryId());
            criteria1.andEqualTo("productId", receiptSetProduct.getProductId());
            List<CategoryProduct> categoryProducts = categoryProductMapper.selectByExample(example1);
            try {
                qwertyui(categoryProducts.get(0), receiptSetProduct);
                minusNum(categoryProducts.get(0), receiptSetProduct);
            } catch (NumberFormatException e) {
                throw new LogicException("金额格式错误");
            }
        }
//        return edit(receiptSet, true);
        mapper.updateByPrimaryKeySelective(receiptSet);
        return receiptSet;
    }

    /**
     * 分页查询
     *
     * @param params
     * @return
     */
    public List<ReceiptSetGetPageNew> getPages(PageParams<ReceiptSetGetPageParams> params) {
        UserManagement user = userManagementMapper.selectByPrimaryKey(params.getParams().getUserId());
        if (user.getDataIsAll() == 1) {
            params.getParams().setIsAdmin(1);
        } else {
            params.getParams().setIsAdmin(2);
        }
        PageHelper.startPage(params.getCurrentPage(), params.getPerPageTotal());
        List<ReceiptSetGetPageNew> pages = mapper.getPage(params.getParams());
        return pages;
    }

    /**
     * 查看
     *
     * @param id
     * @return
     */
    public ReceiptSet view(String id) {
        ReceiptSet receiptSet = mapper.selectByPrimaryKey(id);
        receiptSet.setCategoryName(categoryMapper.selectByPrimaryKey(receiptSet.getCategoryId()).getName());
        receiptSet.setCuserName(userManagementMapper.selectByPrimaryKey(receiptSet.getCuser()).getName());
        Example example = new Example(ReceiptSetProduct.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("receiptId", id);
        List<ReceiptSetProduct> receiptSetProductList = receiptSetProductMapper.selectByExample(example);
        for (ReceiptSetProduct receiptSetProduct : receiptSetProductList) {
            receiptSetProduct.setProduct(productMapper.selectByPrimaryKey(receiptSetProduct.getProductId()));
        }
        receiptSet.setReceiptSetProductList(receiptSetProductList);
        return receiptSet;
    }
}
